#include <iostream>
#include <vector>
#include <string>
#include "Pthread.hpp"
using namespace ThreadModule;

#define NUM 4

// pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; // 锁也是共享资源
int ticketnum = 1000;                             // 共享资源

class ThreadData
{
public:
    std::string name;
    pthread_mutex_t *lock_ptr;
};

void Ticket(ThreadData& td)
{
    while (true)
    {
        pthread_mutex_lock(td.lock_ptr); // 加锁
        if (ticketnum > 0)
        {
            usleep(1000);

            // 1.抢票
            std::cout << td.name << " get a new ticket, id: "<< ticketnum <<std::endl;
            ticketnum--;

            pthread_mutex_unlock(td.lock_ptr); // 解锁

            // 2.入库模拟
            usleep(50);
        }
        else
        {
            pthread_mutex_unlock(td.lock_ptr); // 解锁
            break;
        }
    }
}

int main()
{
    pthread_mutex_t lock;
    pthread_mutex_init(&lock, nullptr);

    std::vector<Thread<ThreadData>> threads;

    // 1.构建线程对象
    for (int i = 0; i < NUM; i++)
    {
        ThreadData* td = new ThreadData();
        td->lock_ptr = &lock;
        threads.emplace_back(Ticket, *td);
        td->name = threads[i].Name();
    }

    // 2.启动线程
    for (auto &thread : threads)
    {
        thread.Start();
    }

    // 3.等待线程
    for (auto &thread : threads)
    {
        thread.Join();
    }

    pthread_mutex_destroy(&lock);

    return 0;
}